<template>
  <div>
    <el-dialog :visible.sync="visiable" width="400px" title="修改邮箱" @close="close()" @open="open()">
      <el-form :rules="rules" :model="user" ref="user" class="add-border">
        <el-form-item prop="newEmail" label="新邮箱：" class="add-border" style="margin-left: 10px;">
          <el-input
            class="content"
            v-model="user.newEmail"
            style="width: 250px; font-size: 14px;"
          ></el-input>
        </el-form-item>

        <div style="display: flex;" class="add-border">
          <el-button
            type="primary"
            style="margin-left: auto; margin-right: 0px;"
            @click="update()"
          >修 改</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ChangeEmail",
  data() {
    return {
      visiable: false,

      user: {
        newEmail: "",
      },

      rules: {
        newEmail: [
          { pattern: /^(\w)+@(\S)+$/, message: "非法邮箱", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    init() {
      this.visiable = true;
    },
    open() {
      this.user.newEmail = "";
    },
    close() {
      this.user.newEmail = "";
      this.$refs.user.resetFields();
    },
    update() {
      this.$refs.user.validate((valid) => {
        if (valid) {
          var url = process.env.URL_HEAD + "/touser/user/page/update/info";

          this.$http
            .get(url, {
              params: {
                name: "email",
                value: this.user.newEmail,
              },
              withCredentials: true,
            })
            .then(
              (response) => {
                if (response.data.status == "ok") {
                  this.visiable = false;

                  this.$emit("updateEmail", this.user.newEmail);
                  this.$message.success("修改成功！");
                } else {
                  this.$message.error("修改失败");
                }
              },
              (response) => {
                this.$message.error("系统异常，请重试");
              }
            );
        } else {
          this.$message.error("请正确输入");
        }
      });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.add-border {
  border: 1px solid #ffffff;
}

.grid-content {
  height: 30px;
}
</style>
